<template>
  <div class="auditor-main">
    <!-- 添加 -->
    <el-card class="box-card" shadow="never">

      <el-button v-no-more-click:3000 type="primary" class="add-invoice" @click="addAuditor">添加</el-button>
      <!-- <el-button type="info" class="add-invoice" @click="exportAll">导出</el-button> -->
      <span class="down-execel">
        <Poptip v-model="showFilter" placement="bottom-end">
          <i class="el-icon-search poptip-condition-add"></i>
          <a href="javascript:;" class='poptip-condition-add'>列表查找</a>
          <div slot="content">
            <Poptip v-model="showFilterCondition" placement="bottom-start" class='poptip-condition'>
              <i class="el-icon-plus"></i>
              <!-- <a href="javascript:;" @click='getAllAgent'>添加过滤条件</a> -->
              <a href="javascript:;">添加过滤条件</a>

              <div slot="content" class="condition-list">
                <ul>
                  <li v-for="(item, index) in columns" :key="index" class='poptip-condition-item' @click="addFilterCondition(item)">{{item.label}}</li>
                </ul>
              </div>
            </Poptip>

            <el-form :model="conditionForm" ref="conditionForm" label-width="120px" class="demo-dynamic" @submit.native.prevent>
              <el-form-item
                v-for="(condition, index) in conditionForm.condition"
                :label="condition.label"
                :key="condition.key"
                :prop="'condition.' + index + '.value'"
                :rules="{
                    required: true, message: condition.label + '不能为空', trigger: 'blur'
                }">
                <el-date-picker
									v-model="submitTime"
									type="daterange"
									placeholder="选择日期"
									value-format="yyyy-MM-dd"
									size="small"
									:validate-event='false'
									@input = 'changInput'
									v-if='condition.label === "注册时间"'>
								</el-date-picker>

                <el-date-picker
									v-model="updateTime"
									type="daterange"
									placeholder="选择日期"
									value-format="yyyy-MM-dd"
									size="small"
									:validate-event='false'
									@input = 'changInput'
									v-else-if='condition.label === "更新时间"'>
								</el-date-picker>

                <el-input v-else size="small" v-model="condition.value"  @keyup.enter.native="submitsearch('conditionForm')"></el-input>
                <el-button @click.stop="removeDomain(condition)" size="mini">删除</el-button>
              </el-form-item>
            </el-form>

            <div class="btns">
              <el-button @click="submitsearch('conditionForm')" size="mini">查询</el-button>
              <el-button @click="resetForm('conditionForm')" size="mini">重置</el-button>
            </div>
          </div>
        </Poptip>
      </span>

    </el-card>

    <el-table
      id="IMTable"
      :data="tableData"
      border
      style="width: 100%"
      height="82%"
      v-loading="loading"
      ref="multipleTable"
      tooltip-effect="dark"
      @sort-change='tableSortChange'
      @selection-change="handleSelectionChange">
      <!-- <el-table-column show-overflow-tooltip type="selection" width="55"></el-table-column> -->
      <el-table-column show-overflow-tooltip prop="id" label="ID" width="60" align="left">
		    <template slot-scope="scope">{{(scope.$index+1)+(currentPage-1)*tableSize}}</template>
	    </el-table-column>
      <el-table-column show-overflow-tooltip prop="name" label="姓名" width="150" align="left" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip prop="phone" label="手机号码" align="left"  width="180" sortable='custom'></el-table-column>
      <el-table-column show-overflow-tooltip prop="email_work" label="工作邮箱" align="left"  sortable='custom' min-width="110"></el-table-column>
      <el-table-column show-overflow-tooltip prop="created_at" label="注册时间" width="250" align="left" sortable='custom'>
        <template slot-scope="scope">{{ scope.row.created_at | formatTime }}</template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="updated_at" label="更新时间" width="250" align="left" sortable='custom'>
        <template slot-scope="scope">{{ scope.row.updated_at | formatTime }}</template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="180">
        <template slot-scope="scope">
          <el-button v-no-more-click:3000 type="primary" size="small" @click="editInvoices(scope.row)">编辑</el-button>
          <el-button v-no-more-click:3000 type="danger" size="small" @click="delAuditor(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="pageSizes"
      :page-size="Number(pageSize)"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 添加弹出框 -->
    <dialogAdd ref="addDialog" @changeList="search"></dialogAdd>

    <!-- 修改 -->
    <dialogEdit ref="editDialog" @changeList="search"></dialogEdit>
  </div>
</template>
<script>
import { getAuditor, delUser } from "~/api/user";
import dialogAdd from "~/components/addUser";
import dialogEdit from "~/components/editUser";
export default {
  head: {
    title: "审核员管理"
  },
  name: "auditor",
  data() {
    return {
		total:0,
      loading: false,
      tableData: [],
      checkTable: [],
      tableSize: 10, //一页几条
      currentPage: 1, //目前在第几页
      pageSizes: [25, 50], //一页可以几条
      showFilter: false, // 控制显示筛选条件
      showFilterCondition: false,
      conditionForm: {
        condition: []
      }, //筛选条件
      columns: [
        {
          label: '姓名',
          id: 1,
          parameter: 'name'
        },
        {
          label: '手机号',
          id: 2,
          parameter: 'phone'
        },
        {
          label: '工作邮箱',
          id: 4,
          parameter: 'email_work'
        },
        {
          label: '注册时间',
          id: 6,
          parameter: 'submitTime'
        },
        {
          label: '更新时间',
          id: 7,
          parameter: 'updateTime'
        },
      ],
      paramsByUser: {
        role_id: 3,
      },
      submitTime: [],
      updateTime: []
    };
  },
  components: {
    dialogAdd,
    dialogEdit
  },
  async asyncData({ $axios }) {
    let res = await getAuditor($axios);
    let obj = {
      loading: false
    };
    if (res.data.code == 200) {
		  obj.total = res.data.page.total;
      obj.tableData = res.data.data;
      obj.pageSize = obj.tableData.length;
      obj.tableSize = obj.tableData.length;
      obj.tableEnd = obj.tableData.length;
    }
    return obj;
  },
  methods: {
    //编辑
    editInvoices(val) {
      this.$refs.editDialog.showDialog("3", val.id);
    },
    //添加
    addAuditor() {
      this.$refs.addDialog.showDialog("3");
    },

    // 删除
    delAuditor(val) {
      this.$confirm("是否确定删除代理人?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        center: true,
        type: "warning"
      })
        .then(() => {
          delUser(this.$axios, val.id)
            .then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                //刷新数据
                // this.changeData();
                this.search()
              } else {
                console.log(res);
              }
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除"
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    //刷新数据
    onChangeList() {
      this.changeData();
    },
    //获取新数据
    changeData() {
      getAuditor(this.$axios)
        .then(res => {
          this.tableData.splice(0, this.tableData.length, ...res.data.data);
          this.pageSize = this.tableData.length;
          this.tableSize = this.tableData.length;
          this.tableEnd = this.tableData.length;
        })
    },

    // 多选
    handleSelectionChange(val) {
      this.checkTable = val;
    },
    exportAll() {},

    //选择一页几条
    handleSizeChange(size) {
      this.paramsByUser.perPage = size
      this.paramsByUser.page = 1
      getAuditor(this.$axios, this.paramsByUser)
      .then(res => {
        if (res.data.code == 200) {
          this.tableData = res.data.data;
          this.total = res.data.page.total
          this.pageSize = res.data.page.per_page
          this.tableSize = res.data.page.per_page
          this.tableEnd = res.data.page.per_page
        }
      })
    },
    //选择第几页
    handleCurrentChange(currentPage) {
      let params = this.paramsByUser
      params.page = currentPage
      this.currentPage = currentPage;
      getAuditor(this.$axios, params)
      .then(res => {
        this.tableData.splice(0, this.tableData.length, ...res.data.data);
        this.pageSize = this.tableData.length;
        this.tableSize = this.tableData.length;
        this.tableEnd = this.tableData.length;
      })
    },
    async search() {
      this.currentPage = 1
      for (var i = 0; i < this.conditionForm.condition.length; i++) {
        let a = this.conditionForm.condition[i].parameter
        this.paramsByUser[a] = this.conditionForm.condition[i].value


         if (this.conditionForm.condition[i].parameter === 'submitTime') {
          this.paramsByUser.created_start_time = this.submitTime[0]
          this.paramsByUser.created_end_time = this.submitTime[1]
        }
         if (this.conditionForm.condition[i].parameter === 'updateTime') {
          this.paramsByUser.updated_start_time = this.updateTime[0]
          this.paramsByUser.updated_end_time = this.updateTime[1]
        }
      }

      // 处理分页数据
			delete this.paramsByUser.page

      delete this.paramsByUser.sort_str
      delete this.paramsByUser.sort_order
      this.$refs['multipleTable'].clearSort()
      this.loading = true
      this.$axios.get('api/user', {
        params: this.paramsByUser
      })
      .then( res => {
        if (res.data.code == '200') {
          this.loading = false
          this.tableData = res.data.data
          this.total = res.data.page.total
          this.showFilter = false
        } else {
          this.$message.error('服务器繁忙')
        }

      } )


    },

    // 添加条件筛选
    addFilterCondition(item) {
      let filterItem = {
        value: '',
        label: item.label,
        parameter: item.parameter,
        key: Date.now()
      }

      if (this.conditionForm.condition.length > 0) {
        let conditionlabels = []
        for (let i = 0; i < this.conditionForm.condition.length; i++) {
          conditionlabels.push(this.conditionForm.condition[i].label)
        }
        let Check = conditionlabels.indexOf(item.label)
        Check == -1 ? this.conditionForm.condition.push(filterItem) : this.$message.error('请勿重复添加')
      } else {
        this.conditionForm.condition.push(filterItem)
      }

      this.showFilterCondition = false;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.$refs['multipleTable'].clearSort()
      this.conditionForm.condition.forEach(v => {
        if (v.value) {
          v.value = null
        }
      });
      this.showFilterCondition = false
      this.submitTime = []
      this.updateTime = []
      this.paramsByUser = {
        role_id: 3
      }
      this.$nextTick(() => {
        this.$refs[formName].clearValidate()
      })
      // this.onChangeList()
      // this.showFilter = false
    },
    submitsearch(formName) {
      let that = this
      this.$refs[formName].validate((valid, prop) => {
        // this.$refs[formName].clearValidate();
        let props = []
        for (let k in prop) {
          props.push(prop[k][0].field)

          if (prop[k][0].message = '注册时间不能为空') {
            if(that.submitTime) {
              if(	that.submitTime.length > 0	) {
                that.$refs[formName].clearValidate([prop[k][0].field])
                let timeIndex = props.indexOf('注册时间不能为空')
                props.splice(timeIndex, 1)
              }
            } else {
              return false
            }
          }
          if (prop[k][0].message = '更新时间不能为空') {
            if(that.updateTime) {
              if(	that.updateTime.length > 0	) {
                that.$refs[formName].clearValidate([prop[k][0].field])
                let timeIndex = props.indexOf('更新时间不能为空')
                props.splice(timeIndex, 1)
              }
            } else {
              return false
            }
          }
        }
        if (props.length) {
          that.$refs[formName].validateField(props, (valid2) => {
            if (valid2) {
              return false;
            } else {
              that.search()
            }

          })
        } else {
          that.search()
        }
      })
    },
    removeDomain(item) {
      this.showFilter = true
      delete this.paramsByUser[item.parameter]
      let index = this.conditionForm.condition.indexOf(item)
      if (index !== -1) {
        this.conditionForm.condition.splice(index, 1)
      }
      if (item.label === '注册时间') {
          this.submitTime = []
          delete this.paramsByUser.created_start_time
					delete this.paramsByUser.created_end_time
      }
      if (item.label === '更新时间') {
          this.updateTime = []
          delete this.paramsByUser.updated_start_time
					delete this.paramsByUser.updated_end_time
      }
      this.search()
    },
    changInput () {
      this.$refs['conditionForm'].clearValidate();
    },
    tableSortChange(column) {
      if (column.order === 'descending') {
        this.paramsByUser.sort_str = column.prop
        this.paramsByUser.sort_order = 'desc'
      } else if (column.order === 'ascending'){
        this.paramsByUser.sort_str = column.prop
        this.paramsByUser.sort_order = 'asc'
      } else {
        delete this.paramsByUser.sort_str
        delete this.paramsByUser.sort_order
      }
      this.loading = true;
      this.$axios.get('api/user', {
        params: this.paramsByUser
      })
      .then(res => {
        if (res.data.code == '200') {
          this.loading = false;
          this.tableData = res.data.data
          this.total = res.data.page.total
          this.pageSize = res.data.page.per_page;
          this.tableSize = res.data.page.per_page
          this.tableEnd = res.data.page.per_page;
        } else {
          this.$message.error('服务器繁忙')
        }
      })
			}
  }
};
</script>
<style lang='less'>
  .auditor-main {
    height: 100%; //撑满表格
    .el-table {
      width: 99.9% !important;
    }
  }
  .el-main .ivu-poptip .ivu-poptip-popper .ivu-poptip-content .ivu-poptip-inner {
		min-width: 450px;
		// height: 300px;
		overflow-y: scroll;
	}

	.el-main .poptip-condition .ivu-poptip-popper .ivu-poptip-content .ivu-poptip-inner {
		min-width: 180px;
	}

	.demo-dynamic {
		padding-left: 10px;

		.el-form-item {
			margin-bottom: 12px;
		}

		.el-input {
			width: 240px;
		}

		.el-date-editor {
			width: 240px;
		}

		.el-button {
			padding: 9px 15px;
			vertical-align: baseline;
		}

		.el-form-item__error {
			padding-top: 0;
		}
	}

	.poptip-condition {
		display: block;
		margin-top: 10px;

		.poptip-condition-item {
			line-height: 25px;
			cursor: pointer;
		}

		.poptip-condition-add {
			font-size: 14px;
		}
	}

	.btns {
		margin-top: 10px;
	}
</style>
